package com.avic.gateway.filter;

import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @author: huangsheng
 * @date: 2018/8/25
 */
@Slf4j
public class ResponseBodyPostFilter extends AbstractZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 8;
    }

    @Override
    public boolean shouldFilter() {
        return shouldFilter(ResponseBodyPostFilter.class.getSimpleName());
    }

    @Override
    public Object run() {
        try {
            RequestContext requestContext = RequestContext.getCurrentContext();
            InputStream inputStream = requestContext.getResponseDataStream();
            if (null != inputStream) {
                byte[] responseDataByteArr = StreamUtils.copyToByteArray(inputStream);
                String responseStr = StreamUtils.copyToString(new ByteArrayInputStream(responseDataByteArr), Charset.defaultCharset());
                log.info("URI {}: response body {}", requestContext.getRequest().getRequestURI(), responseStr);
                requestContext.setResponseBody(responseStr);
            }
        } catch (IOException e) {
            log.warn("设置response body回流异常");
        }
        return null;
    }
}
